package com.hk.dyeyuesystem;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.model.AccountBookRelation;
import com.hk.dyeyuesystem.model.Book;
import com.hk.dyeyuesystem.model.vo.AccountBookRelationVO;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.SqlUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查看相关操作控制层
 */
public class QueryActivity extends AppCompatActivity {

    private TabHost tabHost;

    //  Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView bookListView,currentListView,comeToGoListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query);
        tabHost = findViewById(android.R.id.tabhost);
        // Initialize tabhost
        tabHost.setup();
        // Instantiation layoutinflater
        LayoutInflater inflater = LayoutInflater.from(this);
        // To load XML
        inflater.inflate(R.layout.activity_book, tabHost.getTabContentView());
        inflater.inflate(R.layout.activity_subscribe, tabHost.getTabContentView());
        inflater.inflate(R.layout.activity_le_pass, tabHost.getTabContentView());
        // Add tab
        tabHost.addTab(tabHost.newTabSpec("activity_book").setIndicator("图书查询").setContent(R.id.book_query2));
        tabHost.addTab(tabHost.newTabSpec("activity_subscribe").setIndicator("个人借书查阅").setContent(R.id.book_subscribe2));
        tabHost.addTab(tabHost.newTabSpec("activity_le_pass").setIndicator("过往借阅").setContent(R.id.le_pass));

        //        实例化
        dbOpenHelper = new DBOpenHelper(QueryActivity.this, "db_book_system", null, 1);
//        获取listView控制权
        bookListView = findViewById(R.id.query_book_list_view);
        currentListView = findViewById(R.id.query_current_book_list_view);
        comeToGoListView = findViewById(R.id.query_come_to_go_book_list_view);
//        提取登录信息
        Intent intent = getIntent();
        final Bundle bundle = intent.getExtras();
//        TabHos 触发切换TabHost事件
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if (tabId.equals("activity_book")) { //图书查询
                    Log.e("activity_book", "进入了======");
                    /**
                     * 查询出所有的图书信息并进行回显
                     */
                    findAllBook();
                } else if (tabId.equals("activity_subscribe")) { // 个人借书查询
                    Log.e("activity_subscribe", "进入了======");
                    String loginId = (String) bundle.get("loginId");
                    // TODO: 2021/12/22 查询出此账号预约的书籍，此处预约即表示借出，真正借出需要结合管理人员手动扫码标识借出记录(已解决)
                    /**
                     * 查询此账号当日预约的书籍并进行回显
                     */
                    SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                    findByAId(readableDatabase, loginId, 2);
                } else if (tabId.equals("activity_le_pass")) { // 过往借阅
                    String loginId = (String) bundle.get("loginId");
                    Log.e("activity_le_pass", "进入了======");
                    SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                    /**
                     * 查询此账号以前借阅的记录
                     */
                    findByAId(readableDatabase, loginId, 3);
                }
            }
        });

    }

    /**
     * 查询出该账号的书籍借阅记录
     *
     * @param readableDatabase 数据库对象
     * @param loginId          账号ID
     * @param i                表示 2：当日记录 3：以前记录
     */
    private void findByAId(SQLiteDatabase readableDatabase, String loginId, int i) {
//        当前日期
        String dateString = DateUtil.dateString(new Date(), "yyyy-MM-dd");
        String[] s = null;
        String where = "";
//        个人借书查询
        if (i == 2) {
            where = "AID = ? AND CREATE_TIME LIKE ? AND RETURN_TIME >= ? ";
            s = new String[]{loginId, SqlUtil.likeJoint(dateString), dateString};
        }
//        过往借阅查询
        if (i == 3) {
            where = "AID = ? AND CREATE_TIME < ?";
            s = new String[]{loginId, dateString};
        }
        List<AccountBookRelation> accountBookRelationList = new ArrayList<>();
        Cursor cursor = readableDatabase.query("ACCOUNT_BOOK_RELATION", null, where, s, null, null, null);
        /**
         * 判断是否具有借阅记录
         *  有，进行封装
         *  没有，则进行提示
         */
        while (cursor.moveToNext()) {
            Integer aid = null;
            Integer bid = null;
            Integer status = null;
            try {
                aid = Integer.valueOf(cursor.getString(1));
                bid = Integer.valueOf(cursor.getString(2));
                status = Integer.valueOf(cursor.getString(3));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("QueryActivity.java", "数据不能转化为数字,请检查！");
            }
            String returnTime = cursor.getString(4);
//            封装为对象
            AccountBookRelation accountBookRelation = new AccountBookRelation(aid, bid, status, returnTime);
//            添加入借阅记录
            accountBookRelationList.add(accountBookRelation);
        }
        if (accountBookRelationList.size() == 0 || accountBookRelationList == null) {
            toast = ToastUtil.toastHint(toast, QueryActivity.this, "暂无借阅记录!");
            return;
        }
//        具有借阅记录
        /**
         * 遍历借阅记录，通过图书ID查询所属图书编号和名称并进行封装
         * 用图书归还日期判断当前借阅状态是归还逾期还是借阅中
         *  如果图书归还日期大于或等于今天，证明借阅中，如果小于当天，就证明归还已逾期
         */
//        Initialize List
        List<AccountBookRelationVO> accountBookRelationVOList = new ArrayList<>();
        for (AccountBookRelation accountBookRelation : accountBookRelationList) {
//            账号ID
            Integer aid = accountBookRelation.getAid();
//            图书ID
            Integer bid = accountBookRelation.getBid();
//            预计归还日期
            String returnTimeString = accountBookRelation.getReturnTimeString();
//            图书借阅状态
            Integer status2 = accountBookRelation.getStatus();

//             通过图书ID查询图书信息，如果没有，则提示图书已不存在
            Book book = null;
            Cursor query = readableDatabase.query("BOOK", null, "ID = ?", new String[]{bid.toString()}, null, null, null);
            while (query.moveToNext()) {
                String bookNumber = query.getString(1);
                String bookName = query.getString(2);
//                通过构造函数进行封装
                book = new Book(bookNumber,bookName);
            }
//            判断该图书是否存在
            if (book == null) {
//                当前日期
                long time = new Date().getTime();
                long returnTime = DateUtil.stringDate(returnTimeString).getTime();
                String status = status2 == 1 ? "借阅中" : "已预约";
//                判断当前借阅书籍状态
                if (returnTime < time) {
                    status = "已逾期";
                }
                if (status2 == 2) {
                    status = "已归还";
                }
                AccountBookRelationVO accountBookRelationVO = new AccountBookRelationVO("0","*******",returnTimeString,status);
//                添加借阅记录集合
                accountBookRelationVOList.add(accountBookRelationVO);
                continue;
            }
            //                当前日期
            long time = DateUtil.stringDate(DateUtil.dateString(new Date(),"yyyy-MM-dd")).getTime();
            long returnTime = DateUtil.stringDate(returnTimeString).getTime();
            String status = status2 == 1 ? "借阅中" : "已预约";
//                判断当前借阅书籍状态
            if (returnTime < time) {
                status = "已逾期";
            }
            if (status2 == 2) {
                status = "已归还";
                AccountBookRelationVO accountBookRelationVO = new AccountBookRelationVO(book.getBookNumber(),book.getBookName(),returnTimeString,status);
//                添加借阅记录集合
                accountBookRelationVOList.add(accountBookRelationVO);
                continue;
            }
//            判断借阅的书籍是否处于挂失阶段
            /**
             * 1、通过借阅记录额账号ID和图书ID查询是否具有挂失记录
             *  1.1、如果有，则状态修改为挂失状态
             *  1.2、没有则不变
             */
//            挂失状态：0 挂失中 1：已处理 2：已归还
            String lossStatus = "-1";
            Cursor loss_record = readableDatabase.query("LOSS_RECORD", null, "AID = ? AND BID = ?", new String[]{aid.toString(), bid.toString()}, null, null, null);
            while (loss_record.moveToNext()) {
                lossStatus = loss_record.getString(3);
            }
            int parseInt = Integer.parseInt(lossStatus);
//            挂失中
            if (parseInt == 0) status = "挂失中" ;
//            已处理
            if (parseInt == 1) status = "已处理" ;
//            已归还
            if (parseInt == 2) status = "已归还" ;
            AccountBookRelationVO accountBookRelationVO = new AccountBookRelationVO(book.getBookNumber(),book.getBookName(),returnTimeString,status);
//                添加借阅记录集合
            accountBookRelationVOList.add(accountBookRelationVO);
        }

//        判断借阅记录是否为空
        if (accountBookRelationVOList.size() <= 0) {
            toast = ToastUtil.toastHint(toast, QueryActivity.this, "暂时没有借阅记录，请预约后查看！");
            return;
        }
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(50);
        for (AccountBookRelationVO accountBookRelationVO : accountBookRelationVOList) {
            Map<String, Object> map = new HashMap<>(8);
            //                对数据进行封装
            map.put("bookNumber", accountBookRelationVO.getBookNumber());
            map.put("bookName", accountBookRelationVO.getBookName());
            map.put("returnTime", accountBookRelationVO.getReturnTime());
            map.put("status", accountBookRelationVO.getStatus());
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
//        进行封装，列表展示
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                QueryActivity.this,
                resultList,
                R.layout.query_book,
                new String[]{
                        "bookNumber", "bookName",
                        "returnTime", "status"
                },
                new int[]{
                        R.id.query_current_book_number, R.id.query_current_book_name,
                        R.id.query_current_return_time, R.id.query_current_book_status
                }
        );
        if (i == 2) {
            currentListView.setAdapter(simpleAdapter);
        }
        if (i == 3) {
            comeToGoListView.setAdapter(simpleAdapter);
        }
    }

    /**
     * 首次进入加载数据
     */
    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.e("QueryActivity", "首次进入默认加载第一个Tabhost======");
        /**
         * 查询出所有的图书信息并进行回显
         */
        findAllBook();
    }


    /**
     * 查询出所有的图书
     */
    private void findAllBook() {
//        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursor = readableDatabase.query("BOOK", null, null, null, null, null, null);
//        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(50);

        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>(8);
            String bookNumber = cursor.getString(1);
            String bookName = cursor.getString(2);
            String author = cursor.getString(3);
            String press = cursor.getString(4);
            Integer bookCount = null, bookRemaining = null;
            try {
                bookCount = Integer.valueOf(cursor.getString(5));
                bookRemaining = Integer.valueOf(cursor.getString(6));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("QueryActivity.java", "数据不能转化为数字,请检查！");
            }
//                对数据进行封装
            map.put("bookNumber", bookNumber);
            map.put("bookName", bookName);
            map.put("author", author);
            map.put("press", press);
            map.put("bookCount", bookCount);
            map.put("bookRemaining", bookRemaining);
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
//        判断是否具有图书
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, QueryActivity.this, "暂时没有图书，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                QueryActivity.this,
                resultList,
                R.layout.query_book,
                new String[]{
                        "bookNumber", "bookName",
                        "author", "press",
                        "bookCount", "bookRemaining"
                },
                new int[]{
                        R.id.book_number, R.id.book_name,
                        R.id.book_author, R.id.book_press,
                        R.id.book_count, R.id.book_remaining
                }
        );
        bookListView.setAdapter(simpleAdapter);

    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}
